import requests
import json
import urllib3
from dtos.result import Result
from enumobjects.general_enum import YesOrNoEnum

urllib3.disable_warnings()


class RequestUtil(object):
    def __init__(self, url, timeout=0.25, headers=None):
        self.url = url
        self.timeout = timeout
        self.headers = {
            "content-type": "application/json"
        } if not headers else headers

    @staticmethod
    def _response(res=None, message=""):
        if not message:
            data = res.text if res.status_code == 502 else res.json()
            return Result.get_result(data=data, is_success=YesOrNoEnum.YES.value if res.
                                     status_code == 200 else YesOrNoEnum.NO.value,
                                     message=res.status_code)
        return Result.error_result(message=message)

    def post(self, data):
        try:
            res = requests.post(url=self.url, data=json.dumps(data), timeout=self.timeout, headers=self.headers,
                                verify=False)
            r = self._response(res=res)
            return r
        except Exception as ex:
            return self._response(message=str(ex))

    def get(self, params):
        try:
            res = requests.get(url=self.url, params=params, timeout=self.timeout, verify=False, headers=self.headers)
            return self._response(res=res)
        except Exception as ex:
            return self._response(message=str(ex))
